package com.xindaoapp.happypet.utils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Map;

import org.apache.http.impl.cookie.BasicClientCookie;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuth;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.sina.weibo.sdk.exception.WeiboException;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.UiError;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.listener.SocializeListeners.UMDataListener;
import com.umeng.socialize.exception.SocializeException;
import com.xindaoapp.happypet.BaiduMapManager;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.XDHttpClient;
import com.xindaoapp.happypet.activity.MainActivity;
import com.xindaoapp.happypet.api.ConstantsValue;
import com.xindaoapp.happypet.application.AccessTokenKeeper;
import com.xindaoapp.happypet.application.HappyPetApplication;
import com.xindaoapp.happypet.bean.PetInfo;
import com.xindaoapp.happypet.bean.User;
import com.xindaoapp.happypet.fragments.CreateUserFragment;
import com.xindaoapp.happypet.protocol.MoccaApi;
import com.xindaoapp.happypet.utils.CommonParameter.UserState;
import com.xindaoapp.happypet.utils.Constants.LOGINMODE;

public class LoginManager {
    /** 微博 Web 授权类，提供登陆等功能 */
    private WeiboAuth mWeiboAuth;
    /** 封装了 "access_token"，"expires_in"，"refresh_token"，并提供了他们的管理功能 */
    private Oauth2AccessToken mAccessToken;
    /** 注意：SsoHandler 仅当 SDK 支持 SSO 时有效 */
    public static SsoHandler mSsoHandler;
    private final Activity mContext;
    private boolean isBind;
    private boolean isAutoLogin;
    private IRequest<LOGINMODE> iBindRequest;

    public LoginManager(Activity context) {
        super();
        mContext = context;
    }

    public LoginManager(Activity context, boolean isBind, IRequest<LOGINMODE> iBindRequest) {
        super();
        mContext = context;
        this.isBind = isBind;
        this.iBindRequest = iBindRequest;
    }

    /**
     * 自动登录
     */
    public void autoLogin() {
        isAutoLogin = true;
        if (MoccaPreferences.Logged.get()) {
            int mode = MoccaPreferences.LOGIN_MODE.get();
            if (mode == LOGINMODE.NORMAL.ordinal()) {
                login(MoccaPreferences.UserName.get(), MoccaPreferences.PassWord.get());
            } else if (mode == LOGINMODE.QQ.ordinal()) {
                loginByQQ(MoccaPreferences.QQ_CONUIN.get(), MoccaPreferences.QQ_CONUINSECRET.get(),
                        MoccaPreferences.QQ_OPEN_ID.get());
            } else if (mode == LOGINMODE.SINA.ordinal()) {
                loginBySina(MoccaPreferences.SINA_UID.get(),
                        MoccaPreferences.SINA_ACCESS_TOKEN.get(),
                        MoccaPreferences.SINA_EXPIRES_IN.get());
            }
        } else {
            new BaiduMapManager().initBaiduMaps();
        }
    }

    private void loginBySina(String sina_uid, String token, String oauth2_expiretime) {
        loginBySina(null, sina_uid, token, oauth2_expiretime);
    }

    private void loginBySina(final ProgressHUD progressDialog, String sina_uid, String token,
            String oauth2_expiretime) {
        HappyPetApplication
                .get()
                .getMoccaApi()
                .loginBySina(sina_uid, token, oauth2_expiretime,
                        new IRequest<Map<String, Object>>() {

                            @Override
                            public void request(Map<String, Object> t) {
                                if (progressDialog != null) {
                                    try {
                                        progressDialog.cancel();
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                                parseLoginResult(LOGINMODE.SINA, t, false, null);
                            }
                        });
    }

    private void LoginByWeiXin(final ProgressHUD progressHUD, Bundle value, String content) {
        HappyPetApplication
                .get()
                .getMoccaApi()
                .loginByWeiXin(String.valueOf(value.get("expires_in")),
                        String.valueOf(value.get("openid")),
                        String.valueOf(value.get("access_token")), content,
                        new IRequest<Map<String, Object>>() {
                            @Override
                            public void request(Map<String, Object> t) {
                                // System.out.println(t);
                                if (progressHUD != null)
                                    try {
                                        progressHUD.cancel();
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                parseLoginResult(LOGINMODE.WeiXin, t, false, null);
                            }
                        });
    }

    private void loginByQQ(String conuin, String conuinsecret, String conopenid) {
        loginByQQ(null, conuin, conuinsecret, conopenid);
    }

    private void loginByQQ(final ProgressHUD progressDialog, String conuin, String conuinsecret,
            String conopenid) {
        HappyPetApplication.get().getMoccaApi()
                .loginByQQ(conuin, conuinsecret, conopenid, new IRequest<Map<String, Object>>() {

                    @Override
                    public void request(Map<String, Object> t) {
                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.cancel();
                        }
                        parseLoginResult(LOGINMODE.QQ, t, false, null);
                    }
                });
    }

    public void login(String username, String password) {
        login(null, username, password);
    }

    public void login(final ProgressHUD progressDialog, final String username, final String password) {
        HappyPetApplication.get().getMoccaApi()
                .login(username, password, new IRequest<Map<String, Object>>() {

                    @Override
                    public void request(Map<String, Object> t) {
                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.cancel();
                        }
                        if (t != null && t.containsKey(MoccaApi.RESPONSE_USERINFO)) {
                            MoccaPreferences.UserName.put(username);
                            MoccaPreferences.PassWord.put(password);
                        }
                        parseLoginResult(LOGINMODE.NORMAL, t, false, null);
                    }
                });
    }

    /**
     * 注册
     * 
     * @param name
     * @param psw
     * @param email
     */
    public void register(final String name, final String psw, String email) {
        HappyPetApplication.get().getMoccaApi()
                .register(name, psw, email, new IRequest<Map<String, Object>>() {

                    @Override
                    public void request(Map<String, Object> t) {
                        if (t != null && t.containsKey(MoccaApi.RESPONSE_USERINFO)) {
                            MoccaPreferences.UserName.put(name);
                            MoccaPreferences.PassWord.put(psw);
                        }
                        parseLoginResult(LOGINMODE.NORMAL, t, false, null);
                    }
                });
    }

    /**
     * 区分是否为自动登录
     * 
     * @param isAutoLogin 是否是自动登录
     * @param t
     */
    private void parseLoginResult(final LOGINMODE mode, Map<String, Object> t, boolean notFinish,
            IRequest<User> iRequest) {
        if (t != null) {
            int result = Integer.parseInt(t.get(MoccaApi.RESPONSE_RESULT).toString());
            if (result == 0 && t.containsKey(MoccaApi.RESPONSE_USERINFO)) {// 登录成功
                // 绑定成功的回调，填写邀请码用

                if (mode.ordinal() == LOGINMODE.NORMAL.ordinal()) {
                    MoccaPreferences.LOGIN_MODE.put(LOGINMODE.NORMAL.ordinal());
                } else if (mode.ordinal() == LOGINMODE.QQ.ordinal()) {
                    MoccaPreferences.LOGIN_MODE.put(LOGINMODE.QQ.ordinal());
                } else if (mode.ordinal() == LOGINMODE.SINA.ordinal()) {
                    MoccaPreferences.LOGIN_MODE.put(LOGINMODE.SINA.ordinal());
                } else if (mode.ordinal() == LOGINMODE.WeiXin.ordinal()) {
                    MoccaPreferences.LOGIN_MODE.put(LOGINMODE.WeiXin.ordinal());
                }

                // 积分提示
                User user = (User) t.get(MoccaApi.RESPONSE_USERINFO);
                if (iRequest != null)
                    iRequest.request(user);
                if (!TextUtils.isEmpty(user.jifentishi) && !notFinish) {
                    CommonUtil.showDialog2(mContext, user.jifentishi);
                }

                UserState.setUser(user);
                CommonUtil.registerJpush(mContext, "uid_" + UserState.getUserUid());
                MoccaPreferences.Logged.put(true);

                ConstantsValue.cookieStore = XDHttpClient.client.getCookie();
                BasicClientCookie cookie = new BasicClientCookie("leepet[source]", "android");
                cookie.setDomain(".chinapet.com");
                cookie.setPath("/");
                ConstantsValue.cookieStore.addCookie(cookie);

                mContext.sendBroadcast(new Intent(Constants.ACTION_RECEIVED_NOTICE));
                mContext.sendBroadcast(new Intent(Constants.ACTION_LOGIN_STATE_CHANGED));
                if (!isAutoLogin) {
                    if (isBind) {
                        Toast.makeText(mContext, "绑定成功！", Toast.LENGTH_SHORT).show();
                        iBindRequest.request(mode);
                    } else {
                        Toast.makeText(mContext, "登录成功！", Toast.LENGTH_SHORT).show();
                    }
                    if (!notFinish) {
                        HappyPetApplication.mHandler.postDelayed(new Runnable() {

                            @Override
                            public void run() {
                                if (!mContext.isFinishing()) {
                                    if (isBind) {

                                    } else {
                                        mContext.setResult(Activity.RESULT_OK, null);
                                        mContext.finish();
                                    }
                                }
                            }
                        }, 500);
                    }
                }

                // 初始化宠物列表
                HappyPetApplication.get().getMoccaApi()
                        .getMyPetList(UserState.getUserUid(), new IRequest<PetInfo>() {

                            @Override
                            public void request(PetInfo t) {
                                UserState.setPetInfo(t);
                            }
                        });

                // 手机用户信息
                new BaiduMapManager().initBaiduMaps();
            } else if (result == 101) {// 未绑定
                Toast.makeText(mContext, t.get(MoccaApi.RESPONSE_MSG).toString(),
                        Toast.LENGTH_SHORT).show();

                // 判断是绑定还是提示已绑定
                if (!UserState.isLogged()) {
                    // if (fragment != null) {
                    // Bundle bundle = new Bundle();
                    // bundle.putInt(Constants.KEY_LOGIN_TYPE, mode.ordinal());
                    // fragment.startFragment(new CreateUserFragment(), bundle);
                    // } else if (isBind) {
                    Intent intent = new Intent(mContext, MainActivity.class);
                    intent.putExtra(Constants.KEY_SKIP_CLASS_NAME,
                            CreateUserFragment.class.getCanonicalName());
                    Bundle bundle = new Bundle();
                    bundle.putInt(Constants.KEY_LOGIN_TYPE, mode.ordinal());
                    intent.putExtra(Constants.KEY_BUNDLE, bundle);
                    mContext.startActivity(intent);
                    // }
                }

            } else {// 其他错误
                // 绑定shibai的回调，填写邀请码用
                if (iRequest != null)
                    iRequest.request(null);
                Toast.makeText(mContext, t.get(MoccaApi.RESPONSE_MSG).toString(),
                        Toast.LENGTH_SHORT).show();
            }
        } else {
            if (!isAutoLogin) {
                Toast.makeText(mContext, R.string.net_error, Toast.LENGTH_SHORT).show();
            }
        }
    }

    public void loginQQ(boolean isLogin) {
        String text = "";
        if (isLogin) {
            text = "正在登录请稍候...";
        } else {
            text = "正在绑定请稍候...";
        }
        final ProgressHUD show = ProgressHUD.show(mContext, text, true, true, null);


        HappyPetApplication.get().getUMController()
                .doOauthVerify(mContext, SHARE_MEDIA.QQ, new UMAuthListener() {
                    @Override
                    public void onStart(SHARE_MEDIA platform) {
                        // Toast.makeText(mContext, "授权开始", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onError(SocializeException e, SHARE_MEDIA platform) {
                        Toast.makeText(mContext, "授权错误", Toast.LENGTH_SHORT).show();
                        if (show != null) {
                            show.cancel();
                        }
                    }

                    @Override
                    public void onComplete(Bundle value, SHARE_MEDIA platform) {
                        MoccaPreferences.QQ_OPEN_ID.put(value.getString("openid"));
                        MoccaPreferences.QQ_CONUINSECRET.put("");
                        MoccaPreferences.QQ_CONUIN.put(value.getString("access_token"));

                        // MoccaPreferences.QQ_USERPARM.put(response.toString());
                        // try {
                        // MoccaPreferences.QQ_NICKNAME.put(new JSONObject(response.toString())
                        // .getString("nickname"));
                        // } catch (JSONException e) {
                        // e.printStackTrace();
                        // }
                        loginByQQ(show, value.getString("access_token"),
                                MoccaPreferences.QQ_CONUINSECRET.get(), value.getString("openid"));
                    }

                    @Override
                    public void onCancel(SHARE_MEDIA platform) {
                        if (show != null) {
                            show.cancel();
                        }
                        Toast.makeText(mContext, "授权取消", Toast.LENGTH_SHORT).show();
                    }
                });


        // HappyPetApplication.get().getQqAuth().logout(mContext);
        // HappyPetApplication.get().getTencent().logout(mContext);
        // IUiListener listener = new BaseUiListener(show) {
        // @Override
        // public void onComplete(Object response) {
        // QQInfo qq = JSON.parseObject(response.toString(), QQInfo.class);
        // MoccaPreferences.QQ_OPEN_ID.put(qq.openid);
        // MoccaPreferences.QQ_CONUINSECRET.put("");
        // MoccaPreferences.QQ_CONUIN.put(qq.access_token);
        // updateUserInfo(show);
        // }
        //
        // @Override
        // public void onError(UiError e) {
        // if (show != null) {
        // show.dismiss();
        // }
        // Toast.makeText(mContext, "授权失败", Toast.LENGTH_SHORT).show();
        // super.onError(e);
        // }
        //
        // };
        // HappyPetApplication.get().getTencent().login(mContext, "all", listener);
    }

    private class BaseUiListener implements IUiListener {

        private final ProgressHUD progressHUD;

        public BaseUiListener(ProgressHUD show) {
            this.progressHUD = show;
        }

        @Override
        public void onComplete(Object response) {
            if (progressHUD != null) {
                progressHUD.cancel();
            }
            doComplete((JSONObject) response);
        }

        protected void doComplete(JSONObject values) {}

        @Override
        public void onError(UiError e) {
            if (progressHUD != null) {
                progressHUD.cancel();
            }
            Log.i("onComplete:", "出错了" + e.errorCode);
        }

        @Override
        public void onCancel() {
            if (progressHUD != null) {
                progressHUD.cancel();
            }
            Log.i("onCancel:", "");
        }
    }

    public void loginSina(boolean isLogin) {
        String text = "";
        if (isLogin) {
            text = "正在登录请稍候...";
        } else {
            text = "正在绑定请稍候...";
        }

        ProgressHUD progressHUD = ProgressHUD.show(mContext, text, true, true, null);
        // 创建微博实例
        mWeiboAuth =
                new WeiboAuth(mContext, com.xindaoapp.happypet.application.Constants.APP_KEY,
                        com.xindaoapp.happypet.application.Constants.REDIRECT_URL,
                        com.xindaoapp.happypet.application.Constants.SCOPE);
        // if (mSsoHandler == null) {
        mSsoHandler = new SsoHandler(mContext, mWeiboAuth);
        // }
        mSsoHandler.authorize(new AuthListener(progressHUD));
    }


    public void loginWeixin(boolean isLogin) {
        String text = "";
        if (isLogin) {
            text = "正在登录请稍候...";
        } else {
            text = "正在绑定请稍候...";
        }
        final ProgressHUD progressHUD = ProgressHUD.show(mContext, text, true, true, null);
        UMSocialService mController = UMServiceFactory.getUMSocialService("com.umeng.login");

        // 添加微信平台
        // UMWXHandler wxHandler =
        // new UMWXHandler(mContext, "wx05c050d8b7b4b210", "c1716f0ee2cdce329fbca7af5758d288");
        // wxHandler.addToSocialSDK();

        mController.doOauthVerify(mContext, SHARE_MEDIA.WEIXIN, new UMAuthListener() {


            @Override
            public void onError(SocializeException e, SHARE_MEDIA platform) {
                // System.out.println("授权错误");
                if (progressHUD != null)
                    progressHUD.cancel();
                Toast.makeText(mContext, "授权错误", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onComplete(final Bundle value, SHARE_MEDIA platform) {
                // if (progressHUD != null)
                // progressHUD.dismiss();
                if (value != null) {
                    MoccaPreferences.WEIXIN_EXPIRES_IN.put(value.getString("expires_in"));
                    MoccaPreferences.WEIXIN_ACCESS_TOKEN.put(value.getString("access_token"));
                    MoccaPreferences.WEIXIN_OPENID.put(value.getString("openid"));

                    getWeiXinUserInfo(String.valueOf(value.get("openid")),
                            String.valueOf(value.get("access_token")),
                            new AsyncHttpResponseHandler() {
                                @Override
                                public void onSuccess(String content) {
                                    // System.out.println(content);
                                    MoccaPreferences.WEIXIN_USERPAREMS.put(content);
                                    com.xindaoapp.happypet.utils.User user =
                                            com.xindaoapp.happypet.utils.User.parse(content);
                                    if (user != null) {
                                        // Toast.makeText(mContext, "获取User信息成功，用户昵称：" +
                                        // user.screen_name,
                                        // Toast.LENGTH_LONG).show();
                                        MoccaPreferences.WeiXin_USER_NAME.put(user.nickname);

                                        LoginByWeiXin(progressHUD, value, content);
                                    } else {
                                        Toast.makeText(mContext, content, Toast.LENGTH_LONG).show();
                                    }

                                    super.onSuccess(content);
                                }

                                @Override
                                public void onFailure(Throwable error, String content) {
                                    super.onFailure(error, content);
                                }


                            });

                    // LoginByWeiXin(progressHUD, value);
                } else {
                    if (progressHUD != null)
                        progressHUD.cancel();
                }

                if (value != null && !TextUtils.isEmpty(value.getString("uid"))) {
                    // Toast.makeText(mContext, "授权成功" + value.getString("uid"), Toast.LENGTH_SHORT)
                    // .show();
                } else {
                    Toast.makeText(mContext, "授权失败", Toast.LENGTH_SHORT).show();
                }
            }


            @Override
            public void onCancel(SHARE_MEDIA arg0) {
                // System.out.println("授权取消");
                Toast.makeText(mContext, "授权取消", Toast.LENGTH_SHORT).show();
                if (progressHUD != null)
                    progressHUD.cancel();
                super.onCancel(arg0);
            }

            @Override
            public void onStart(SHARE_MEDIA platform) {
                if (progressHUD != null)
                    progressHUD.cancel();
                // System.out.println("授权开始");
                // Toast.makeText(mContext, "授权开始", Toast.LENGTH_SHORT).show();
            }
        });


        mController.getPlatformInfo(mContext, SHARE_MEDIA.WEIXIN, new UMDataListener() {
            @Override
            public void onStart() {
                // Toast.makeText(mContext, "登陆授权中，请稍后...", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onComplete(int status, Map<String, Object> info) {
                if (status == 200 && info != null) {

                    // System.out.println("登陆返回数据..." + info);
                    // StringBuilder sb = new StringBuilder();
                    // Set<String> keys = info.keySet();
                    // for (String key : keys) {
                    // sb.append(key + "=" + info.get(key).toString() + "\r\n");
                    // }
                    // Log.d("TestData", sb.toString());
                    // Toast.makeText(mContext, sb.toString(), 1).show();
                } else {
                    Log.d("TestData", "发生错误：" + status);
                }
            }
        });
    }

    public void getWeiXinUserInfo(String openid, String access_token,
            AsyncHttpResponseHandler handler) {
        RequestParams params = new RequestParams();
        params.add("openid", openid);
        params.add("access_token", access_token);
        if (openid == null || access_token == null) {
            return;
        }
        XDHttpClient.get2("https://api.weixin.qq.com/sns/userinfo", params, handler);
    }



    class UMAuthListener implements
            com.umeng.socialize.controller.listener.SocializeListeners.UMAuthListener {

        @Override
        public void onCancel(SHARE_MEDIA arg0) {

        }

        @Override
        public void onComplete(Bundle arg0, SHARE_MEDIA arg1) {

        }

        @Override
        public void onError(SocializeException arg0, SHARE_MEDIA arg1) {

        }

        @Override
        public void onStart(SHARE_MEDIA arg0) {

        }

    }

    /**
     * 微博认证授权回调类。 1. SSO 授权时，需要在 {@link #onActivityResult} 中调用 {@link SsoHandler#authorizeCallBack}
     * 后， 该回调才会被执行。 2. 非 SSO 授权时，当授权结束后，该回调就会被执行。 当授权成功后，请保存该 access_token、expires_in、uid 等信息到
     * SharedPreferences 中。
     */
    class AuthListener implements WeiboAuthListener {
        private final ProgressHUD progressHUD;

        public AuthListener(ProgressHUD progressHUD) {
            this.progressHUD = progressHUD;
        }

        @Override
        public void onComplete(final Bundle values) {
            mAccessToken = Oauth2AccessToken.parseAccessToken(values);
            if (mAccessToken.isSessionValid()) {
                // 显示 Token
                // updateTokenView(false);

                // 保存 Token 到 SharedPreferences
                AccessTokenKeeper.writeAccessToken(mContext, mAccessToken);
                // Toast.makeText(mContext, R.string.weibosdk_demo_toast_auth_success,
                // Toast.LENGTH_SHORT).show();

                MoccaPreferences.SINA_UID.put(values.getString("uid"));
                MoccaPreferences.SINA_ACCESS_TOKEN.put(values.getString("access_token"));
                MoccaPreferences.SINA_EXPIRES_IN.put(values.getString("expires_in"));

                show(values.getString("uid"), new AsyncHttpResponseHandler() {

                    @Override
                    public void onSuccess(String response) {
                        super.onSuccess(response);
                        com.xindaoapp.happypet.utils.User user =
                                com.xindaoapp.happypet.utils.User.parse(response);
                        if (user != null) {
                            // Toast.makeText(mContext, "获取User信息成功，用户昵称：" + user.screen_name,
                            // Toast.LENGTH_LONG).show();
                            MoccaPreferences.SINA_USER_NAME.put(user.screen_name);

                            loginBySina(progressHUD, values.getString("uid"),
                                    values.getString("access_token"),
                                    values.getString("expires_in"));
                        } else {
                            Toast.makeText(mContext, response, Toast.LENGTH_LONG).show();
                        }
                    }

                    @Override
                    public void onFailure(Throwable error, String content) {
                        super.onFailure(error, content);
                    }
                });
            } else {
                // 以下几种情况，您会收到 Code：
                // 1. 当您未在平台上注册的应用程序的包名与签名时；
                // 2. 当您注册的应用程序包名与签名不正确时；
                // 3. 当您在平台上注册的包名和签名与您当前测试的应用的包名和签名不匹配时。
                String code = values.getString("code");
                String message = mContext.getString(R.string.weibosdk_demo_toast_auth_failed);
                if (!TextUtils.isEmpty(code)) {
                    message = message + "\nObtained the code: " + code;
                }
                Toast.makeText(mContext, message, Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public void onCancel() {
            if (progressHUD != null) {
                progressHUD.cancel();
            }
            Toast.makeText(mContext, "取消授权", Toast.LENGTH_LONG).show();
        }

        @Override
        public void onWeiboException(WeiboException e) {
            if (progressHUD != null) {
                progressHUD.cancel();
            }
            Toast.makeText(mContext, "Auth exception : " + e.getMessage(), Toast.LENGTH_LONG)
                    .show();
        }
    }

    public void show(String uid, AsyncHttpResponseHandler listener) {
        RequestParams params = new RequestParams();
        params.add("uid", uid);
        requestAsync("https://api.weibo.com/2/users/show.json", params, "GET", listener);
    }

    protected void requestAsync(String url, RequestParams params, String httpMethod,
            AsyncHttpResponseHandler listener) {
        if (null == mAccessToken || TextUtils.isEmpty(url) || null == params
                || TextUtils.isEmpty(httpMethod) || null == listener) {
            // LogUtil.e(TAG, "Argument error!");
            return;
        }

        params.put("source", "3675845370");
        params.put("access_token", mAccessToken.getToken());
        // AsyncWeiboRunner.requestAsync(url, params, httpMethod, listener);
        XDHttpClient.get2(url, params, listener);
    }

    private void updateTokenView(boolean hasExisted) {
        String date =
                new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new java.util.Date(mAccessToken
                        .getExpiresTime()));
        String format = mContext.getString(R.string.weibosdk_demo_token_to_string_format_1);
        Toast.makeText(mContext, String.format(format, mAccessToken.getToken(), date),
                Toast.LENGTH_SHORT).show();

        String message = String.format(format, mAccessToken.getToken(), date);
        if (hasExisted) {
            message = mContext.getString(R.string.weibosdk_demo_token_has_existed) + "\n" + message;
        }
        Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
    }

    /**
     * 检查用户名是否存在并且自动登录
     */
    public void quickLoginByQQ(String username, final boolean notFinish,
            final IRequest<User> iRequest) {
        HappyPetApplication
                .get()
                .getMoccaApi()
                .quickLoginByQQ(username, MoccaPreferences.QQ_CONUIN.get(),
                        MoccaPreferences.QQ_CONUINSECRET.get(), MoccaPreferences.QQ_OPEN_ID.get(),
                        MoccaPreferences.QQ_USERPARM.get(), new IRequest<Map<String, Object>>() {

                            @Override
                            public void request(Map<String, Object> t) {
                                parseLoginResult(LOGINMODE.QQ, t, notFinish, iRequest);
                            }
                        });
    }

    public void quickLoginBySina(String username, final boolean notFinish,
            final IRequest<User> iRequest) {
        HappyPetApplication
                .get()
                .getMoccaApi()
                .quickLoginBySina(username, MoccaPreferences.SINA_UID.get(),
                        MoccaPreferences.SINA_ACCESS_TOKEN.get(),
                        MoccaPreferences.SINA_EXPIRES_IN.get(),
                        new IRequest<Map<String, Object>>() {
                            @Override
                            public void request(Map<String, Object> t) {
                                parseLoginResult(LOGINMODE.SINA, t, notFinish, iRequest);
                            }
                        });
    }

    public void quickLoginByWeiXin(String username, final boolean notFinish,
            final IRequest<User> iRequest) {
        HappyPetApplication
                .get()
                .getMoccaApi()
                .quickLoginByWeiXin(username, MoccaPreferences.WEIXIN_EXPIRES_IN.get(),
                        MoccaPreferences.WEIXIN_OPENID.get(),
                        MoccaPreferences.WEIXIN_ACCESS_TOKEN.get(),
                        new IRequest<Map<String, Object>>() {
                            @Override
                            public void request(Map<String, Object> t) {
                                parseLoginResult(LOGINMODE.WeiXin, t, notFinish, iRequest);
                            }
                        });
    }

    public void bindSina(String username, String password) {
        HappyPetApplication
                .get()
                .getMoccaApi()
                .bindSina(MoccaPreferences.SINA_UID.get(),
                        MoccaPreferences.SINA_ACCESS_TOKEN.get(),
                        MoccaPreferences.SINA_EXPIRES_IN.get(), username, password,
                        new IRequest<Map<String, Object>>() {

                            @Override
                            public void request(Map<String, Object> t) {
                                parseLoginResult(LOGINMODE.SINA, t, false, null);
                            }
                        });
    }

    public void bindQQ(String username, String password) {
        HappyPetApplication
                .get()
                .getMoccaApi()
                .bindQQ(MoccaPreferences.QQ_CONUIN.get(), MoccaPreferences.QQ_CONUINSECRET.get(),
                        MoccaPreferences.QQ_OPEN_ID.get(), username, password,
                        new IRequest<Map<String, Object>>() {

                            @Override
                            public void request(Map<String, Object> t) {
                                parseLoginResult(LOGINMODE.QQ, t, false, null);
                            }
                        });
    }

    /**
     * 获取用户信息
     */
    // private void updateUserInfo(final ProgressHUD progressDialog) {
    // if (HappyPetApplication.get().getQqAuth() != null
    // && HappyPetApplication.get().getQqAuth().isSessionValid()) {
    // IUiListener listener = new BaseUiListener(null) {
    //
    // @Override
    // public void onError(UiError e) {}
    //
    // @Override
    // public void onComplete(final Object response) {
    // MoccaPreferences.QQ_USERPARM.put(response.toString());
    // try {
    // MoccaPreferences.QQ_NICKNAME.put(new JSONObject(response.toString())
    // .getString("nickname"));
    // } catch (JSONException e) {
    // e.printStackTrace();
    // }
    // loginByQQ(progressDialog, MoccaPreferences.QQ_CONUIN.get(),
    // MoccaPreferences.QQ_CONUINSECRET.get(),
    // MoccaPreferences.QQ_OPEN_ID.get());
    // }
    //
    // @Override
    // public void onCancel() {}
    // };
    // UserInfo mInfo =
    // new UserInfo(mContext, HappyPetApplication.get().getQqAuth().getQQToken());
    // mInfo.getUserInfo(listener);
    // }
    // }

    /**
     * 退出登录，清空所有缓存
     */
    public void logout() {
        XDHttpClient.client.getCookie().clear();
        ConstantsValue.cookieStore = null;
        // HappyPetApplication.get().getQqAuth().logout(mContext);
        // HappyPetApplication.get().getTencent().logout(mContext);
        CommonUtil.logoutQQ(mContext);

        MoccaPreferences.Logged.put(false);
        MoccaPreferences.LOGIN_MODE.put(LOGINMODE.NONE.ordinal());
        Constants.NoticeLabel.sHasNewMessageNotice = false;
        mContext.sendBroadcast(new Intent(Constants.KEY_NOTICE_STATE_CHANGED));
        mContext.sendBroadcast(new Intent(Constants.ACTION_LOGIN_STATE_CHANGED));
        UserState.setUser(null);
        UserState.getPetInfo().setArray(new ArrayList<PetInfo.Pet>());
        CommonUtil.registerJpush(mContext, "");
        Toast.makeText(mContext, "退出登录成功", Toast.LENGTH_SHORT).show();
    }



}
